#! coding = utf-8

import os, sys
from time import sleep
import logging, re
import requests

class XiMaHuang(object):
    """ 吸码皇短信接口 """

    def __init__(self):
        # 吸码皇 接口
        self.__dev = ""
        self.__name = "lywudile"
        self.__password = "123456"
        self.__logger = logging
        self.__token = self.__login()
        self.__itemid = "2843" #"1328" 

    def __send_get_request(self, url, retries=0, headers=None):
        """ 发送GET请求 """
        try:
            res = requests.get(url, headers=headers)
            if res.status_code == 200:
                res.encoding = res.apparent_encoding
                return res.text
        except ConnectionResetError:
            if retries > 3:
                self.__logger.error("GET Network error")
                return None
            return self.__send_request(url, retries=retries+1)
        except Exception as e:
            self.__logger.error(str(e))
            return None

    def __send_post_request(self, url, data, headers=None, cookies=None, retries=0):
        """ 发送POST请求"""
        try:
            res = requests.post(url, data = data, headers = headers, proxies=self.__PROXY, cookies=cookies)

            if res.status_code != 200:
                self.__logger.info("[POST FAILED] "+res.text)
                return False

            try:
                data = res.json()
                self.__logger.info(data)
                return data
            except Exception as e:
                self.__logger.error("101"+e)
                return False
        except ConnectionError:
            if retries > 3:
                self.__logger.error("POST Network error")
                return False
            return self.__send_post_request(url, data = data, headers = headers, proxies=self.__PROXY, cookies=cookies, retries=retries+1)
        except Exception as e:
            self.__logger.error("109"+str(e))
            return False

    def __send_options_request(self, url, headers=None, retries=0):
        try:
            res = requests.options(url, headers=headers, proxies=self.__PROXY)


            if res.status_code != 200:
                self.__logger.error("[OPTIONS FAILED] Url: %s, Code: %s, Message: %s" % (url, str(res.status_code), res.text))
                return False
            else:
                self.__logger.info("OPTIONS SUCCESS")
                # self.__logger.info(res.headers)
                return res.headers['Set-Cookie']
        except ConnectionError:
            if retries > 3:
                self.__logger.error("OPTIONS Network error")
                return False
            return self.__send_options_request(self, url, headers=headers, retries=retries+1)
        except Exception as e:
            self.__logger.error("129"+str(e))
            return False

    def __login(self):
        """ 登陆接码平台 """
        name = self.__name
        password = self.__password
        url = "http://www.ximahuang.com/alz/api?action=loginIn&name=%s&password=%s" % (name, password)

        ret = self.__send_get_request(url)
        self.__logger.info(ret)

        if int(ret[0]) == 1:
            return ret[2:]
        else:
            return None

    def get_phone(self):
        """ 获得手机号码 """
        # url = "http://api.fxhyd.cn/UserInterface.aspx?action=getmobile&token=%s&itemid=%s&excludeno=170.171" % (self.__token, self.__itemid)
        url = "http://www.ximahuang.com/alz/api?action=getPhone&sid=%s&token=%s" % (self.__itemid, self.__token)
        self.__logger.info(url)
        ret = self.__send_get_request(url)
        self.__logger.warning(ret)

        if ret is None:
            return False

        if ret.find("没有号码可用") != -1:
            return False

        # 发生错误返回值: 大于零的整数
        try:
            if int(ret[0]) != 1:
                self.__logger.error(ret)
                return False
        except:
            pass

        #正常返回值：success|15948304749
        # phone = ret.split("|")[1].strip()
        phone = ret[2:]

        self.__logger.info("Get phone number: %s" % phone)

        return phone

    def get_sms(self, phone):
        """ 获得短信验证码 """
        # url = "http://api.fxhyd.cn/UserInterface.aspx?action=getsms&token=%s&itemid=%s&mobile=%s&release=1" % (self.__token, self.__itemid, phone)
        url = "http://www.ximahuang.com/alz/api?action=getMessage&sid=%s&phone=%s&token=%s" % (self.__itemid, phone, self.__token)
        self.__logger.info(url)
        for i in range(1,60):
            self.__logger.warning("正在第 {} 次请求".format(i+1))
            res = self.__send_get_request(url)
            self.__logger.warning(res)
            code, content = res.split("|")
            
            if code != "1":
                sleep(1)
                continue

            sms_code = re.findall(r'\d+', content)[0]
            self.__logger.warning("phone: %s，got code: %s" % (phone, sms_code))
            return sms_code

        self.__logger.info("phone: %s，120s did not receive verification code, obsoleted." % phone)
        return None

    def block_phone(self, phone):
        """ 拉黑一个号码 """
        url = "http://www.ximahuang.com/alz/api?action=addBlacklist&sid=%s&phone=%s&token=%s" % (self.__itemid, phone, self.__token)
        self.__logger.info(url)

        res = self.__send_get_request(url)

        # 1|操作成功

        if int(res[0]) == 1:
            return True

        return False

    def release_phone(self, phone):
        """ 释放一个号码 """
        url = "http://www.ximahuang.com/alz/api?action=cancelRecv&sid=%s&phone=%s&token=%s" % (self.__itemid, phone, self.__token)
        self.__logger.info(url)

        res = self.__send_get_request(url)

        # 1|操作成功
        if int(res[0]) == 1:
            return True

        return False